package com.lenovo.manufacture.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.lenovo.manufacture.R;
import com.lenovo.manufacture.activity.TWebView;
import com.lenovo.manufacture.utils.HttpTools;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class Fragment_T61 extends Fragment {


    public Fragment_T61() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint({"SetJavaScriptEnabled"})
    private void initWebView(View view) {

        TWebView webView = new TWebView(view.getContext(), null);
        ViewGroup viewParent = view.findViewById(R.id.cusWB);
        viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        webView.loadUrl("file:///android_asset/carCus.html");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                /* mWebView.showLog("test Log"); */
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                int index = url.indexOf("FORM?");
                String pms = null;
                if (index != -1) {
                    try {
                        pms = URLDecoder.decode(url.substring(index + 5), "UTF-8");
                        String finalPms = pms;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    createOrder(finalPms);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        webView.loadUrl("file:///android_asset/carCus.html");
                    }
                }
            }
        });


        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.setInitialScale(25);
//        webView.addJavascriptInterface(new T7.JavaScriptInterface(this), "nativeMethod");
        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSetting.setSupportZoom(true);
//        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
//        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_t61, container, false);
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initWebView(view);
    }

    public void createOrder(String pms) throws IOException, ParseException {
        Toast.makeText(this.getContext(), "下单成功！", Toast.LENGTH_LONG).show();
        String[] split = pms.split("&");
        for (String s : split) {
            System.out.println(s);
        }
        String date = split[1].split("=")[1];
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(date);
        long time = parse.getTime();
        String times = String.valueOf(time);
        HttpTools.url("/UserAppointment/create")
                .addHeader("Content-Type","application/x-www-form-urlencoded")
                .addHeader("charset","utf-8")
                .addParam("userWorkId", "1")
                .addParam("userAppointmentName", "X")
                .addParam("content", "X")
                .addParam("type", "0")
                .addParam("carId", split[0].split("=")[1])
                .addParam("time", times)
                .addParam("num", split[2].split("=")[1])
                .addParam("gold", "1000")
                .addParam("engine", split[3].split("=")[1])
                .addParam("speed", split[4].split("=")[1])
                .addParam("wheel", split[5].split("=")[1])
                .addParam("control", split[6].split("=")[1])
                .addParam("brake", split[7].split("=")[1])
                .addParam("hang", split[8].split("=")[1])
                .addParam("color", "0")
                .postAsy(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("FAILED"+e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("DONE");
                        System.out.println(response.body().string());
                    }
                });
    }
}